from datetime import datetime, timedelta
from typing import Dict, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
import psutil
import os

from app.api.deps import get_current_active_user, get_db
from app.models.user import User
from app.schemas.dashboard import (
    DashboardStatsResponse,
    SystemStatsResponse,
    RecentActivityResponse,
    ActivityItem
)

router = APIRouter()


@router.get("/stats", response_model=DashboardStatsResponse)
async def get_dashboard_stats(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取控制台统计数据"""
    try:
        # 模拟统计数据（实际项目中应该从数据库查询）
        stats = {
            "total_users": db.query(User).count(),
            "active_users": db.query(User).filter(User.is_active == True).count(),
            "total_tasks": 156,  # 示例数据
            "running_tasks": 12,
            "completed_tasks": 134,
            "failed_tasks": 10,
            "total_crawlers": 8,
            "running_crawlers": 3,
            "ai_models": 5,
            "active_models": 4,
            "data_volume": "2.3TB",
            "daily_requests": 15420,
            "success_rate": 98.5
        }
        
        return DashboardStatsResponse(**stats)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计数据失败: {str(e)}")


@router.get("/system", response_model=SystemStatsResponse)
async def get_system_stats(
    current_user: User = Depends(get_current_active_user)
):
    """获取系统状态信息"""
    try:
        # 获取系统信息
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # 获取进程数量
        process_count = len(psutil.pids())
        
        # 获取网络信息
        network = psutil.net_io_counters()
        
        # 获取系统启动时间
        boot_time = datetime.fromtimestamp(psutil.boot_time())
        uptime = datetime.now() - boot_time
        
        system_stats = {
            "cpu_usage": round(cpu_percent, 1),
            "memory_usage": round(memory.percent, 1),
            "memory_total": round(memory.total / (1024**3), 2),  # GB
            "memory_used": round(memory.used / (1024**3), 2),    # GB
            "disk_usage": round(disk.percent, 1),
            "disk_total": round(disk.total / (1024**3), 2),      # GB
            "disk_used": round(disk.used / (1024**3), 2),        # GB
            "network_sent": round(network.bytes_sent / (1024**2), 2),  # MB
            "network_recv": round(network.bytes_recv / (1024**2), 2),  # MB
            "processes": process_count,
            "uptime_days": uptime.days,
            "uptime_hours": uptime.seconds // 3600,
            "uptime_minutes": (uptime.seconds % 3600) // 60
        }
        
        return SystemStatsResponse(**system_stats)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取系统信息失败: {str(e)}")


@router.get("/activities", response_model=RecentActivityResponse)
async def get_recent_activities(
    current_user: User = Depends(get_current_active_user),
    limit: int = 10
):
    """获取最近活动记录"""
    try:
        # 模拟最近活动数据（实际项目中应该从数据库查询）
        user_id = 1  # 模拟用户ID
        activities = [
            ActivityItem(
                id=1,
                type="task",
                title="数据爬虫任务完成",
                description="成功抓取了1000条新闻数据",
                timestamp=datetime.now() - timedelta(minutes=5),
                status="success",
                user_id=user_id
            ),
            ActivityItem(
                id=2,
                type="system",
                title="AI模型训练启动",
                description="开始训练新的文本分类模型",
                timestamp=datetime.now() - timedelta(minutes=15),
                status="running",
                user_id=user_id
            ),
            ActivityItem(
                id=3,
                type="user",
                title="用户登录",
                description=f"用户 {current_user.username} 成功登录系统",
                timestamp=datetime.now() - timedelta(minutes=30),
                status="info",
                user_id=user_id
            ),
            ActivityItem(
                id=4,
                type="task",
                title="定时任务执行",
                description="每日数据备份任务执行完成",
                timestamp=datetime.now() - timedelta(hours=1),
                status="success",
                user_id=user_id
            ),
            ActivityItem(
                id=5,
                type="system",
                title="系统更新",
                description="系统组件更新到最新版本",
                timestamp=datetime.now() - timedelta(hours=2),
                status="success",
                user_id=user_id
            ),
            ActivityItem(
                id=6,
                type="alert",
                title="内存使用率告警",
                description="系统内存使用率超过80%",
                timestamp=datetime.now() - timedelta(hours=3),
                status="warning",
                user_id=user_id
            ),
            ActivityItem(
                id=7,
                type="task",
                title="数据处理失败",
                description="批量数据处理任务执行失败",
                timestamp=datetime.now() - timedelta(hours=4),
                status="error",
                user_id=user_id
            ),
            ActivityItem(
                id=8,
                type="crawler",
                title="爬虫任务启动",
                description="启动电商数据采集爬虫",
                timestamp=datetime.now() - timedelta(hours=6),
                status="running",
                user_id=user_id
            )
        ]
        
        # 限制返回数量
        activities = activities[:limit]
        
        return RecentActivityResponse(
            total=len(activities),
            activities=activities
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取活动记录失败: {str(e)}")


@router.get("/quick-stats")
async def get_quick_stats(
    current_user: User = Depends(get_current_active_user)
):
    """获取快速统计信息"""
    try:
        # 获取今日、昨日、本周、本月的简要统计
        now = datetime.now()
        today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
        yesterday_start = today_start - timedelta(days=1)
        week_start = today_start - timedelta(days=now.weekday())
        month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        
        quick_stats = {
            "today": {
                "tasks_completed": 23,
                "data_processed": "150MB",
                "api_calls": 1240,
                "success_rate": 97.8
            },
            "yesterday": {
                "tasks_completed": 31,
                "data_processed": "200MB",
                "api_calls": 1580,
                "success_rate": 96.5
            },
            "this_week": {
                "tasks_completed": 185,
                "data_processed": "1.2GB",
                "api_calls": 8920,
                "success_rate": 97.2
            },
            "this_month": {
                "tasks_completed": 756,
                "data_processed": "4.8GB",
                "api_calls": 35600,
                "success_rate": 96.8
            }
        }
        
        return {"data": quick_stats}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取快速统计失败: {str(e)}")